<?php 
class UserVote extends Base
{
    public function loadById($id)
    {
        // TODO: Implement loadById() method.
    }


    protected function getPrimaryKey()
    {
        // TODO: Implement getPrimaryKey() method.
    }

    protected function getTableName()
    {
        return "application_vote";
    }


    public function loadUsersByVoteId($voteid)
    {
        return $this->_db->getall("select * from user_vote uv left join user u on uv.applicationId=u.applicationId and uv.voteid=" . $voteid);
    }

    /**添加投票
     * @return void
     */
    public function vote($voteId, $applicationId)
    {
        //看看今天有没有被投过
        $sql = "select count(1) as count from application_vote where applicationId=$applicationId and voteId= $voteId and to_days(createDate)=to_days(now())";
        $count = $this->_db->getone($sql);
        if ($count['count'] == 0) {
            $sql = "insert into application_vote(applicationId,voteId,createDate) values ($applicationId,$voteId,now())";
            $ret = $this->_db->query($sql);
        }
        $sql = "update application_vote set amount=amount+1 where applicationId=" . $applicationId . " and voteId=" . $voteId . " and to_days(createDate)=to_days(now())";
        $ret = $this->_db->update($sql);

    }


    /**每周人气之星
     * @return void
     */
    public function dayStar($voteId)
    {
        $sql = "select a.* from " . $this->getTableName() . " uv left join applications a on uv.voteId = a.voteId and uv.applicationId=a.applicationId where  uv.voteId=" . $voteId . " and to_days(now())=to_days(uv.createDate) order by uv.amount desc limit 1";
        return $this->_db->getOne($sql);
    }

    /**往日人气之星
     * @param $voteId
     * @return void
     */
    public function dayStars($voteId, $count)
    {
        $sql = "select * from (select a.*,uv.createDate as voteCreateDate,uv.amount from " . $this->getTableName() . " uv left join applications a on uv.voteId = a.voteId and uv.applicationId=a.applicationId where  uv.voteId=" . $voteId . "  order by uv.amount desc) as result  group by result.voteCreateDate  having to_days(result.voteCreateDate) < to_days(now()) ";
        return $this->_db->getall($sql);
    }

    public function findCountByUserId($applicationId, $voteId)
    {
        $sql = "select sum(amount) as count from " . $this->getTableName() . " where applicationId = $applicationId and voteId= $voteId";
        $count = $this->_db->getOne($sql);
        echo $count['count'] == "" ? 0 : $count['count'];
    }

    public function dayStarMore($voteId, $count)
    {
        $sql = "select a.* from " . $this->getTableName() . " uv left join applications a on uv.voteId = a.voteId and uv.applicationId=a.applicationId where  uv.voteId=" . $voteId . " and to_days(now())=to_days(uv.createDate) order by uv.amount desc limit $count";
        return $this->_db->getall($sql);
    }

}

?>